package com.etcn.modules.busi.member.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.etcn.common.utils.sms.SmsUtil;
import com.etcn.modules.busi.member.constant.ErrorConsts;
import com.etcn.modules.busi.member.dao.IWmMemberDao;
import com.etcn.modules.busi.member.pojo.WmMember;
import com.etcn.modules.busi.member.service.IWmMemberService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etcn.common.Enum.DateFormat;
import com.etcn.common.Enum.MemberState;
import com.etcn.common.Enum.YesOrNo;
import com.etcn.common.jwt.JwtConfig;
import com.etcn.common.jwt.JwtUtil;
import com.etcn.common.pojo.FileUploadVo;
import com.etcn.common.redis.RedisService;
import com.etcn.common.service.impl.CrudServiceImpl;
import com.etcn.common.utils.DataUtil;
import com.etcn.common.utils.DateUtil;
import com.etcn.common.utils.PubFun;
import com.etcn.common.utils.StringUtil;
import com.etcn.common.utils.UploadImageHandler;
import com.etcn.common.utils.UserUtil;
import com.etcn.common.utils.secret.MD5Util;

/**
 * 会员serviceImpl
 * 
 * @author guozc
 * @date 2018-03-09 08:21:55
 */
@Service("wmMemberService")
public class WmMemberServiceImpl extends CrudServiceImpl<IWmMemberDao, WmMember> implements IWmMemberService {

	@Autowired
	private UploadImageHandler uploadImageHandler;
	@Autowired
	private JwtConfig jwtConfig;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private SmsUtil smsUtil;
	@Autowired
	private RedisService redisService;

	@Override
	public Map<String, Object> register(WmMember entity) throws Exception {
		// 参数校验
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		WmMember member = dao.getByMobile(entity.getMobile());
		if (member != null) {
			PubFun.renderError(ErrorConsts.MOBILE_ALREADY_EXIST);
		}
		if (StringUtils.isEmpty(entity.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_NOT_EMPTY);
		}
		if (StringUtils.isEmpty(entity.getVerifyCode())) {
			PubFun.renderError(ErrorConsts.VERIFYCODE_NOT_EMPTY);
		}
		// 校验验证码
		smsUtil.checkVerifyCode(entity.getMobile(), entity.getVerifyCode());
		// 新增会员
		String password = entity.getPassword();// 保存未加密密码，下面登录用
		entity.setMemberId(String.valueOf(DataUtil.createUniqueNum(entity.getMobile() + new Date().toString())));
		entity.setPassword(MD5Util.Md5(MD5Util.Md5(password)));
		entity.setStatus(MemberState.NORMAL.value());
		entity.setVipProductId("0");// 默认普通会员
		entity.setVipFlag(YesOrNo.NO.value());
		entity.setCreateTime(new Date());
		dao.insert(entity);
		// 登录
		entity.setPassword(password);
		Map<String, Object> ret = login(entity);

		return ret;
	}

	@Override
	public Map<String, Object> login(WmMember entity) throws Exception {
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		WmMember member = dao.getByMobile(entity.getMobile());
		if (member == null) {
			PubFun.renderError(ErrorConsts.MEMBER_NOT_EXIST);
		}
		if (MemberState.FREEZED.value().equals(member.getStatus())) {
			PubFun.renderError(ErrorConsts.MEMBER_FREEZED);
		}
		if (StringUtils.isEmpty(entity.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_NOT_EMPTY);
		}
		if (!MD5Util.Md5(MD5Util.Md5(entity.getPassword())).equals(member.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_WRONG);
		}
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("member", member);
		// 生产token
		String timestamp = String.valueOf(System.nanoTime());
		String accessToken = jwtUtil.createJWT(member, jwtConfig.getSecret(), timestamp);
		ret.put("securetoken", jwtConfig.getTokenHead() + " " + accessToken);
		// 存储登录标识
		redisService.set(member.getMemberId() + "_loginflag", timestamp, jwtConfig.getExpiration());

		return ret;
	}

	@Override
	public Map<String, Object> loginWithSms(WmMember entity) throws Exception {
		// 参数校验
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		WmMember member = dao.getByMobile(entity.getMobile());
		if (member == null) {
			PubFun.renderError(ErrorConsts.MEMBER_NOT_EXIST);
		}
		if (MemberState.FREEZED.value().equals(member.getStatus())) {
			PubFun.renderError(ErrorConsts.MEMBER_FREEZED);
		}
		if (StringUtils.isEmpty(entity.getVerifyCode())) {
			PubFun.renderError(ErrorConsts.VERIFYCODE_NOT_EMPTY);
		}
		// 校验验证码
		smsUtil.checkVerifyCode(entity.getMobile(), entity.getVerifyCode());
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("member", member);
		// 生产token
		String timestamp = String.valueOf(System.nanoTime());
		String accessToken = jwtUtil.createJWT(member, jwtConfig.getSecret(), timestamp);
		ret.put("securetoken", jwtConfig.getTokenHead() + " " + accessToken);
		// 存储登录标识
		redisService.set(member.getMemberId() + "_loginflag", timestamp, jwtConfig.getExpiration());
		return ret;
	}

	@Override
	public void logout() throws Exception {
		// 删除登录标识
		redisService.remove(UserUtil.getCurrentMemberId() + "_loginflag");
	}

	@Override
	public Map<String, Object> getDetail(String memberId) throws Exception {
		Map<String, Object> ret = new HashMap<String, Object>();
		WmMember member = dao.getByMemberId(memberId);
		if (member == null) {
			PubFun.renderError(ErrorConsts.MEMBER_NOT_EXIST);
		}

		// vip过期处理
		String vipEndTime = member.getVipEndTime();
		if (StringUtils.isNotEmpty(vipEndTime)
				&& DateUtil.timeCompare(DateUtil.formatDateToString(new Date(), DateFormat.Y_M_D_HMS), vipEndTime,
						DateFormat.Y_M_D_HMS) > 0) {
			WmMember entity = new WmMember();
			entity.setVipProductId("0");// 设置成免费套餐
			entity.setVipFlag("0");
			entity.setMemberId(memberId);
			entity.setVipEndTime(null);
			dao.vipExpireUpdate(entity);
		}

		ret.put("member", member);
		return ret;
	}

	@Override
	public Map<String, Object> uploadAvatar(FileUploadVo fileUploadVo) throws Exception {
		// 上传图片
		String headImage = uploadImageHandler.uploadFile(fileUploadVo.getUploadFile(), "headimg",
				fileUploadVo.getMemberId() + "-headimg");
		headImage += "?time=" + System.nanoTime();
		// 更新会员头像信息
		WmMember member = new WmMember();
		member.setMemberId(fileUploadVo.getMemberId());
		member.setHeadImage(headImage);
		dao.updateByMemberId(member);

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("headImage", headImage);
		return ret;
	}

	@Override
	public Map<String, Object> updateByMemberId(WmMember entity) throws Exception {
		// 修改
		dao.updateByMemberId(entity);
		// 返回最新资料
		return getDetail(entity.getMemberId());
	}

	@Override
	public void changePwd(WmMember entity) throws Exception {
		// 校验原密码
		WmMember member = dao.getByMemberId(entity.getMemberId());
		if (member == null) {
			PubFun.renderError(ErrorConsts.MEMBER_NOT_EXIST);
		}
		String oldPassword = MD5Util.Md5(MD5Util.Md5(entity.getOldPassword()));
		if (!member.getPassword().equals(oldPassword)) {
			PubFun.renderError(ErrorConsts.PWD_OLD_WRONG);
		}
		// 设置新密码
		if (StringUtil.isEmpty(entity.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_NOT_EMPTY);
		}
		if (entity.getOldPassword().equals(entity.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_NEW_SHOULD_DIFFER_OLD);
		}
		String newPassword = MD5Util.Md5(MD5Util.Md5(entity.getPassword()));
		entity.setPassword(newPassword);
		dao.updateByMemberId(entity);
	}

	@Override
	public void forgotPwd(WmMember entity) throws Exception {
		// 参数校验
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		WmMember member = dao.getByMobile(entity.getMobile());
		if (member == null) {
			PubFun.renderError(ErrorConsts.MEMBER_NOT_EXIST);
		}
		if (StringUtils.isEmpty(entity.getVerifyCode())) {
			PubFun.renderError(ErrorConsts.VERIFYCODE_NOT_EMPTY);
		}
		if (StringUtils.isEmpty(entity.getPassword())) {
			PubFun.renderError(ErrorConsts.PWD_NOT_EMPTY);
		}
		// 校验验证码
		smsUtil.checkVerifyCode(entity.getMobile(), entity.getVerifyCode());
		// 设置新密码
		String newPassword = MD5Util.Md5(MD5Util.Md5(entity.getPassword()));
		member.setPassword(newPassword);
		dao.updateByMemberId(member);
	}

	@Override
	public void sendRegisterSms(WmMember entity) throws Exception {
		// 参数校验
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		WmMember member = dao.getByMobile(entity.getMobile());
		if (member != null) {
			PubFun.renderError(ErrorConsts.MOBILE_ALREADY_EXIST);
		}
		// 发送短信
		smsUtil.sendVerifyCode(entity.getMobile());
	}

	@Override
	public void sendsms(WmMember entity) throws Exception {
		// 参数校验
		if (StringUtils.isEmpty(entity.getMobile())) {
			PubFun.renderError(ErrorConsts.MOBILE_NOT_EMPTY);
		}
		// 发送短信
		smsUtil.sendVerifyCode(entity.getMobile());
	}

	@Override
	public void payUpdate(WmMember member) throws Exception {
		dao.payUpdate(member);
	}

	@Override
	public void vipExpireUpdate(WmMember member) throws Exception {
		dao.vipExpireUpdate(member);
	}

	@Override
	public WmMember getByMemberId(String memberId) throws Exception {
		return dao.getByMemberId(memberId);
	}

}